/* eslint-disable no-nested-ternary */
/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, DatePicker, Input, Select, Table, message, Spin } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import styles from '@/utils/utils.less';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const { MonthPicker } = DatePicker;
const FormItem = Form.Item;
const { Description } = DescriptionList;
let submitFlag = false;

@connect(({ reducemp, loading }) => ({
  deduPdInfoList: reducemp.deduPdInfoList, // 产品pdInfoList
  deduInsInfoList: reducemp.insInfoList, // 险种insInfoList
  loading:
    loading.effects['reducemp/fetchminusUpdateList'] ||
    loading.effects['reducemp/minusUpdateOver'] ||
    false,
  RemoveRsnList: reducemp.RemoveRsnList, // 离职原因
  minusUpdateList: reducemp.minusUpdateList, // 回显,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      subite: true, // 分项设置
      dateflg: false,
      taskSource: '2',
      insSetFlag: 2,
      sendEndDateLastDay: 31,
    };
  }

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;
    const { sendId, deduTaskId, taskSource = '2' } = query;
    this.setState({ taskSource });
    dispatch({
      type: 'reducemp/reasonsLeaving', // 离职原因
      payload: {},
    });
    dispatch({
      type: 'reducemp/fetchminusUpdateList', // 回显
      payload: { sendDraftId: sendId, deduTaskId },
      callback: response => {
        if (response.data.unempFlag === 1) {
          this.setState({ isTelRequired: true });
        }
        const sendEndDate = (response.data && response.data.sendEndDate) || 31;
        this.setState(
          {
            insSetFlag: response.data.insSetFlag || 2,
            sendEndDateLastDay: Number(sendEndDate.substr(sendEndDate.length - 2, 2)),
          },
          () => {
            if (
              response.data &&
              response.data.insSetFlag === 2 &&
              response.data.deduPdInfoList &&
              response.data.deduPdInfoList.length
            ) {
              response.data.deduPdInfoList.forEach(item => {
                if (
                  item.pdId === 'PDINF_0000000001' &&
                  item.deduInsInfoList &&
                  item.deduInsInfoList.length
                ) {
                  this.subsett();
                }
              });
            }
          }
        );
      },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'reducemp/updateModelData',
      payload: { deduPdInfoList: [] },
    });
  }

  // 设置电话是否是选中状态
  isContact = value => {
    if (value === '1') {
      this.setState({ isTelRequired: true });
    } else {
      this.setState({ isTelRequired: false });
    }
  };

  // 选择业务结束年月 （日期）
  selectEndDate = date => {
    this.setState({
      sendEndDateLastDay: moment(date).daysInMonth(),
    });
  };

  // 分项设置
  subsett = () => {
    const { dispatch, deduPdInfoList, deduInsInfoList } = this.props;
    const dataList = JSON.parse(JSON.stringify(deduPdInfoList));
    this.setState({ subite: false });
    let i = 0;
    dataList.forEach((item, index) => {
      if (item.id === 'PDINF_0000000001') {
        // 社保
        i = index;
      }
    });
    deduInsInfoList.forEach(item => {
      const temp = item;
      temp.id = item.ass;
      temp.name = item.assName;
      temp.endDate = item.endDate;
      temp.cityId = item.cityId;
      temp.cityName = item.cityName;
      dataList.splice(i + 1, 0, item);
      temp.lastDay = moment(item.endDate).daysInMonth();
    });
    dispatch({
      type: 'reducemp/updateModelData', // 离职原因
      payload: { deduPdInfoList: dataList },
    });
    this.setState({ dateflg: true });
  };

  // 取消分项设置
  subsettcancel = () => {
    const { deduPdInfoList, dispatch, form, deduInsInfoList } = this.props;
    this.setState({ subite: true, dateflg: false });
    const arr = JSON.parse(JSON.stringify(deduPdInfoList));
    let i = 0;
    arr.forEach((item, index) => {
      if (item.id === 'PDINF_0000000001') {
        // 社保
        i = index;
        arr[index].endDate = moment(item.endDate);
        arr[index].lastDay = moment(item.endDate).daysInMonth();
        form.setFieldsValue({
          [`endDate_${item.id}`]: moment(item.endDate),
        });
        arr.splice(i + 1, deduInsInfoList.length); // 将五险的数据截取掉
      }
    });

    dispatch({
      type: 'reducemp/updateModelData', // 离职原因
      payload: { deduPdInfoList: arr },
    });
  };

  // 产品属性选择时间时，更新时间
  dateChange = (date, datestring, record) => {
    const { deduPdInfoList, dispatch } = this.props;
    deduPdInfoList.forEach((item, index) => {
      if (`${record.id}` === `${item.id}`) {
        deduPdInfoList[index].lastDay = moment(date).daysInMonth();
      }
    });
    dispatch({
      type: 'reducemp/updateModelData', // 离职原因
      payload: { deduPdInfoList },
    });
  };

  // 处理产品分项设置数据
  processData = data => {
    const { deduPdInfoList } = this.props;
    const deduInsInfoLists = [];
    const deduPdInfoLists = [];
    deduPdInfoList.forEach(item => {
      const id = `${item.id}`;
      if (!item.ass) {
        // 如果没有险种，就没有分项
        deduPdInfoLists.push({
          pdId: id,
          endDate: data[`endDate_${id}`]
            ? data[`endDate_${id}`].format(`YYYY-MM-${item.lastDay}`)
            : '',
          pdCate: item.pdCate,
        });
      } else {
        deduInsInfoLists.push({
          ass: id,
          endDate: data[`endDate_${id}`]
            ? data[`endDate_${id}`].format(`YYYY-MM-${item.lastDay}`)
            : '',
        });
      }
    });
    return { deduInsInfoLists, deduPdInfoLists };
  };

  // 提交数据
  sumSubmit = () => {
    const {
      deduPdInfoList,
      minusUpdateList,
      dispatch,
      form,
      location: { query },
    } = this.props;
    const { deduTaskId } = query;
    const { sendEndDateLastDay } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      const temp = values;
      if (!err) {
        const deduInfoList = this.processData(values);
        deduPdInfoList.forEach(item => {
          delete temp[`endDate_${item.id}`];
        });
        Object.keys(values).forEach(key => {
          if (!values[key]) {
            // 不存在
            temp[key] = '';
          } else if (values[key].key) {
            // 下拉
            temp[key] = values[key].key;
          } else if (key === 'evaDate') {
            // 日期
            temp[key] = values[key].format('YYYY-MM-DD');
          } else if (key === 'sendEndDate') {
            // 日期
            temp[key] = values[key].format(`YYYY-MM-${sendEndDateLastDay}`);
          }
        });
        if (!submitFlag) {
          submitFlag = true;
          dispatch({
            type: 'reducemp/minusUpdateOver', // 提交
            payload: {
              ...values,
              sendDraftId: minusUpdateList.sendDraftId,
              deduPdInfoList: deduInfoList.deduPdInfoLists, //  社保，公积金对象
              deduInsInfoList: deduInfoList.deduInsInfoLists, // 社保的五险
              taskId: deduTaskId,
            },
            callback: response => {
              submitFlag = false;
              if (response.success) {
                message.success(`${response.message || '修改成功！'}`, 3, () => {
                  router.push('/customservicemanage/reduceemployee/index');
                });
              } else {
                message.warning(`${response.message || '修改失败！'}`);
              }
            },
          });
        }

      }
    });
  };

  render() {
    const {
      isTelRequired,
      dateflg,
      subite,
      taskSource,
      insSetFlag,
      sendEndDateLastDay,
    } = this.state;
    const {
      loading,
      RemoveRsnList,
      deduPdInfoList,
      minusUpdateList,
      deduInsInfoList,
      form,
    } = this.props;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: '产品',
        dataIndex: 'name',
        width: 200,
        align: 'center',
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        width: 200,
        align: 'center',
      },
      {
        title: '执行方',
        dataIndex: 'execTypeName',
        width: 200,
        align: 'center',
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        width: 400,
        align: 'center',
        render: (text, record) => (
          <div>
            <FormItem style={{ margin: 0, float: 'left', width: 120 }}>
              {getFieldDecorator(`endDate_${record.id}`, {
                rules: [{ required: true, message: '请选择' }],
                initialValue: record.endDate && moment(record.endDate),
              })(
                <MonthPicker
                  style={{ width: '110%' }}
                  placeholder="请选择"
                  disabled={!!(record.id === 'PDINF_0000000001' && dateflg)}
                  onChange={(date, dateString) => this.dateChange(date, dateString, record)}
                  format={`YYYY-MM-${record.lastDay}`}
                />
              )}
            </FormItem>
            {insSetFlag === 2 && record.id === 'PDINF_0000000001' && deduInsInfoList.length > 0 ? (
              subite === true ? (
                <a
                  style={{ lineHeight: '33px' }}
                  onClick={() => {
                    this.subsett(record);
                  }}
                >
                  分项设置
                </a>
              ) : (
                <a
                  style={{ lineHeight: '33px' }}
                  onClick={() => {
                    this.subsettcancel(record);
                  }}
                >
                  取消分项设置
                </a>
              )
            ) : null}
          </div>
        ),
      },
    ];
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>}>
              <DescriptionList>
                <Description term="客户名称">{minusUpdateList.custName}</Description>
                <Description term="商务合同">{minusUpdateList.custContName}</Description>
                <Description term="报价单">{minusUpdateList.quoName}</Description>
                <Description term="雇员姓名">{minusUpdateList.empName}</Description>
                <Description term="证件类型">{minusUpdateList.idTypeName}</Description>
                <Description term="证件号">{minusUpdateList.idCode}</Description>
                <Description term="入职日期">{minusUpdateList.entryDate}</Description>
              </DescriptionList>
            </Card>
            <Card
              title={
                <span style={{ fontWeight: 'bolder' }}>
                  {taskSource === '3' || taskSource === '4' ? '减少产品信息' : '减员信息'}
                </span>
              }
            >
              {taskSource === '2' ? (
                <div>
                  <Row gutter={64}>
                    <Col {...colProps}>
                      <FormItem label="离职日期">
                        {getFieldDecorator('evaDate', {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue:
                            minusUpdateList.evaDate &&
                            moment(`${minusUpdateList.evaDate}`, 'YYYY-MM-DD'),
                        })(<DatePicker placeholder="请选择" style={{ width: '100%' }} />)}
                      </FormItem>
                    </Col>
                    <Col {...colProps}>
                      <FormItem label="离职原因">
                        {getFieldDecorator('evaReason', {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: minusUpdateList.evaReason
                            ? minusUpdateList.evaReason
                            : undefined,
                        })(
                          <Select
                            placeholder="请选择"
                            style={{ width: '100%' }}
                            showSearch
                            optionFilterProp="children"
                          >
                            {RemoveRsnList.map(item => (
                              <Option key={item.rsgnRsnId} value={item.rsgnRsnId}>
                                {item.rsgnRsnName}
                              </Option>
                            ))}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col {...colProps}>
                      <FormItem label="电话">
                        {getFieldDecorator('mobile', {
                          rules: [
                            // {
                            //   required: isTelRequired,
                            //   message: '最大限制12位',
                            //   pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                            // },
                            {
                              required: isTelRequired,
                              message: '请输入11位手机号码',
                              pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                              max: 12,
                            },
                          ],
                          initialValue: minusUpdateList.mobile ? minusUpdateList.mobile : undefined,
                        })(<Input placeholder="请输入" maxLength={12} />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={64}>
                    <Col {...colProps}>
                      <FormItem label="业务结束日期">
                        {getFieldDecorator('sendEndDate', {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue:
                            minusUpdateList.sendEndDate && moment(`${minusUpdateList.sendEndDate}`),
                        })(
                          <MonthPicker
                            placeholder="请选择"
                            style={{ width: '100%' }}
                            onChange={this.selectEndDate}
                            format={`YYYY-MM-${sendEndDateLastDay}`}
                          />
                        )}
                      </FormItem>
                    </Col>
                    <Col {...colProps}>
                      <FormItem label="是否离职联系">
                        {getFieldDecorator('unempFlag', {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: minusUpdateList.unempFlag
                            ? `${minusUpdateList.unempFlag}`
                            : undefined,
                        })(<DictCode dictType="YES_NO_FLAG" onSelect={this.isContact} />)}
                      </FormItem>
                    </Col>
                    {minusUpdateList.sendType === 1 ? null : (
                      <Col {...colProps}>
                        <FormItem label="是否终止劳动合同">
                          {getFieldDecorator('stopEmpContFlag', {
                            rules: [{ required: false, message: '请选择' }],
                            initialValue: minusUpdateList.stopEmpContFlag
                              ? `${minusUpdateList.stopEmpContFlag}`
                              : undefined,
                          })(<DictCode dictType="YES_NO_FLAG" disabled />)}
                        </FormItem>
                      </Col>
                    )}
                    <Col {...colProps}>
                      <FormItem label="办理备注">
                        {getFieldDecorator('remark', {
                          rules: [{ required: false, message: '请选择' }],
                          initialValue: minusUpdateList.remark ? minusUpdateList.remark : undefined,
                        })(<Input placeholder="请输入" maxLength={200} />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Card type="inner" title="分项产品结束日期设置">
                      <Table
                        rowClassName={styles.editableRowDate}
                        style={{ width: 600 }}
                        columns={columns}
                        dataSource={deduPdInfoList}
                        rowKey={(record, index) => index}
                        bordered
                        size="middle"
                        pagination={false}
                      />
                    </Card>
                  </Row>
                </div>
              ) : (
                <Table
                  rowClassName={styles.editableRowDate}
                  style={{ width: 600 }}
                  columns={columns}
                  dataSource={deduPdInfoList}
                  rowKey={(record, index) => index}
                  bordered
                  size="middle"
                  pagination={false}
                />
              )}
            </Card>
            <FooterToolbar style={{ width: '100%' }}>
              <Button
                onClick={() => router.push('/customservicemanage/reduceemployee/index')}
                style={{ marginRight: 10 }}
              >
                返回
              </Button>
              <Button type="primary" onClick={this.sumSubmit}>
                提交
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default TableList;
